import { defineStore } from 'pinia'
import {ref, computed} from 'vue'
import type {DragResult} from "smooth-dnd";
import {materialsJson} from "@/mocks/materials";
import type {MaterialType} from "@/types/material.type";

export const useSmoothDnd03a = defineStore('smoothDnd03a', () => {
  const materials = ref<MaterialType[]>(materialsJson);// 这是物料库的甩有物料
  const items = ref<MaterialType[]>(materialsJson);// 这是从物料库中选取的
  let selectedItemId = ref<string|null>(null);

  const selectedItem = computed(() => {
    return getSelectedItem();
  });

  function setSelectedItemId(id: string){
    if(selectedItemId.value === id){
      selectedItemId.value = null;
    }else{
      selectedItemId.value = id;
    }
  }

  function getSelectedItem(){
    const item = items.value.find(v => v.id==selectedItemId.value);
    return item;
  }

  /**
   * 末尾追加
   * @param item
   */
  function addItems(item: any) {
    items.value.push(item);
  }

  /**
   * 整体替换
   * @param items
   */
  function replaceAll(newItems: []){
    items.value = [...newItems]
  }

  function updateItemById(item: any){
    const index = items.value.findIndex(v => v.id==item.id);
    if(index!==-1){
      items.value.splice(index, 1, item);
    }
  }

  const applyDrag = <T extends any[]>(arr: T, dragResult: DragResult)=>{
    const result = [...arr];
    const {addedIndex, removedIndex, payload} = dragResult;
    // 这是添加，也就是从外面拖入
    if(addedIndex!==null&&removedIndex===null){
      const newPayload = JSON.parse(JSON.stringify(payload));
      newPayload.id = Math.random().toString();
      result.splice(addedIndex, 0, newPayload);
    }
    // 这是移动，也就是在当前容器内拖动改变顺序
    else if(addedIndex!==null&&removedIndex!==null){
      return  arrayMove(items.value, removedIndex, addedIndex);
    }
    // 这是移动，也就是在当前容器内拖动改变顺序
    else if(addedIndex===null&&removedIndex!==null){
      result.splice(removedIndex, 1);
    }
    return result;
  }
  return { items, addItems, replaceAll, applyDrag, setSelectedItemId, selectedItemId, selectedItem, getSelectedItem, updateItemById, materials}
})
function arrayMove<T>(array: T[], from: number, to: number): T[] {
  const newArray = array.slice()
  newArray.splice(to < 0 ? newArray.length + to : to, 0, newArray.splice(from, 1)[0])

  return newArray
}
